package com.qyhl.module_practice.substreet.trend;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.qyhl.module_practice.R;
import com.qyhl.module_practice.R2;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.glide.GlideRoundTransform;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.Image;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeTrendBean;
import com.qyhl.webtv.commonlib.utils.ResizableImageView;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.NineGridLayout.NineAdapter;
import com.qyhl.webtv.commonlib.utils.view.NineGridLayout.NineLayout;
import com.qyhl.webtv.commonlib.utils.view.imagebrowser.MNImageBrowser;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import static com.qyhl.webtv.commonlib.utils.view.video.emptyvideo.EmptyControlVideoActivity.IntentKey_VideoCover;
import static com.qyhl.webtv.commonlib.utils.view.video.emptyvideo.EmptyControlVideoActivity.IntentKey_VideoUrl;


/**
 * 实践动态
 */
public class PracticeTrendFragment extends BaseFragment implements PracticeTrendContract.PracticeTrendView {
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    private View view;

    private String orgId;

    private PracticeTrendPresenter mPresenter;

    private CommonAdapter<PracticeTrendBean> commonAdapter;

    private List<PracticeTrendBean> mDataList = new ArrayList<>();

    private int page = 1;

    private boolean isTeam = false;

    public void setTeam(boolean team) {
        isTeam = team;
    }

    public void setOrgId(String orgId) {
        this.orgId = orgId;
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return view = inflater.inflate(R.layout.practice_fragment_trend, null);
    }

    @Override
    protected void create() {
        mPresenter = new PracticeTrendPresenter(this);
        loadData();
    }

    @Override
    public void initImmersionBar() {

    }

    @Override
    protected void setListener() {
        setListeners();
    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }

    public static PracticeTrendFragment newInstance(String orgId, boolean isTeam) {
        PracticeTrendFragment fragment = new PracticeTrendFragment();
        fragment.setOrgId(orgId);
        fragment.setTeam(isTeam);
        return fragment;
    }


    /**
     * 加载数据
     */
    private void loadData() {
        //下拉刷新
        initView();

    }


    private void initView() {
        loadMask.setStatus(LoadingLayout.Loading);
        refresh.setEnableLoadMore(true);
        refresh.setRefreshFooter(new ClassicsFooter(getContext()));
        refresh.setRefreshHeader(new MaterialHeader(getContext()));

        recycleView.setLayoutManager(new LinearLayoutManager(getContext()));

        DividerItemDecoration divider = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(getContext(), R.drawable.practice_item_news_divider));
        recycleView.addItemDecoration(divider);
        recycleView.setAdapter(commonAdapter = new CommonAdapter<PracticeTrendBean>(getContext(), R.layout.practice_item_trend, mDataList) {
            @Override
            protected void convert(ViewHolder holder, final PracticeTrendBean bean, int position) {
                holder.setText(R.id.author, bean.getAuthor());

                holder.setText(R.id.date, DateUtils.practiceTrendFormat(bean.getCreateDate()));

                holder.setText(R.id.content, bean.getContent());

                holder.setText(R.id.title, bean.getTitle());

                ImageView videoCover = holder.getView(R.id.video_cover);
                RelativeLayout videoLayout = holder.getView(R.id.video_layout);
                ResizableImageView singleCover = holder.getView(R.id.single_image);
                NineLayout nineLayout = holder.getView(R.id.nine_layout);

                if (bean.getContentType() == 0) {
                    holder.setVisible(R.id.video_layout, false);
                    if (bean.getImgs() != null && bean.getImgs().size() > 0) {
                        if (bean.getImgs().size() == 1) {
                            holder.setVisible(R.id.video_layout, false);
                            holder.setVisible(R.id.single_image, true);
                            holder.setVisible(R.id.nine_layout, false);

                            Glide.with(PracticeTrendFragment.this)
                                    .load(bean.getImgs().get(0).getUrl())
                                    .apply(new RequestOptions().error(R.drawable.cover_normal_default).placeholder(R.drawable.cover_normal_default))
                                    .into(singleCover);

                            singleCover.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    List<Image> imageList = initDatas(bean.getImgs());
                                    ArrayList<String> mList = new ArrayList<>();
                                    for (int i = 0; i < imageList.size(); i++) {
                                        mList.add(imageList.get(i).getUrl());
                                    }
                                    MNImageBrowser.showImageBrowser(getContext(), v, 0, mList);
                                }
                            });
                        } else {
                            holder.setVisible(R.id.video_layout, false);
                            holder.setVisible(R.id.single_image, false);
                            holder.setVisible(R.id.nine_layout, true);

                            nineLayout.setGap(10);
                            List<Image> imageList = initDatas(bean.getImgs());
                            Adapter adapter = new Adapter(getActivity(), imageList);
                            nineLayout.setAdapter(adapter);
                            nineLayout.setOnItemClickListerner(new NineLayout.OnItemClickListerner() {
                                @Override
                                public void onItemClick(View view, int position) {
                                    ;
                                    ArrayList<String> mList = new ArrayList<>();
                                    for (int i = 0; i < bean.getImgs().size(); i++) {
                                        mList.add(bean.getImgs().get(i).getUrl());
                                    }
                                    MNImageBrowser.showImageBrowser(getContext(), view, position, mList);
                                }
                            });
                        }
                    } else {
                        holder.setVisible(R.id.video_layout, false);
                        holder.setVisible(R.id.single_image, false);
                        holder.setVisible(R.id.nine_layout, false);
                    }
                } else if (bean.getContentType() == 1) {
                    holder.setVisible(R.id.video_layout, true);
                    holder.setVisible(R.id.single_image, false);
                    holder.setVisible(R.id.nine_layout, false);

                    if (bean.getImgs() != null && bean.getImgs().size() > 1) {
                        if (bean.getImgs().get(0).getType() == 0) {
                            Glide.with(PracticeTrendFragment.this)
                                    .load(bean.getImgs().get(0).getUrl())
                                    .apply(new RequestOptions().error(R.drawable.cover_normal_default).placeholder(R.drawable.cover_normal_default))
                                    .into(videoCover);

                            videoLayout.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Bundle bundle = new Bundle();
                                    bundle.putString(IntentKey_VideoUrl, bean.getImgs().get(1).getUrl());
                                    bundle.putString(IntentKey_VideoCover, bean.getImgs().get(0).getUrl());
                                    RouterManager.router(ARouterPathConstant.VIDEO_EMPTY_CONTROL, bundle);
                                }
                            });
                        } else {
                            Glide.with(PracticeTrendFragment.this)
                                    .load(bean.getImgs().get(1).getUrl())
                                    .apply(new RequestOptions().error(R.drawable.cover_normal_default).placeholder(R.drawable.cover_normal_default))
                                    .into(videoCover);

                            videoLayout.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                    Bundle bundle = new Bundle();
                                    bundle.putString(IntentKey_VideoUrl, bean.getImgs().get(0).getUrl());
                                    bundle.putString(IntentKey_VideoCover, bean.getImgs().get(1).getUrl());
                                    RouterManager.router(ARouterPathConstant.VIDEO_EMPTY_CONTROL, bundle);
                                }
                            });
                        }
                    } else {
                        holder.setVisible(R.id.video_layout, false);
                    }
                } else {
                    holder.setVisible(R.id.video_layout, false);
                    holder.setVisible(R.id.single_image, false);
                    holder.setVisible(R.id.nine_layout, false);

                }
            }
        });

        mPresenter.getList(orgId, page + "", isTeam);
    }

    private void setListeners() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                page = 1;
                mPresenter.getList(orgId, page + "", isTeam);
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                mPresenter.getList(orgId, page + "", isTeam);
            }
        });

        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getList(orgId, page + "", isTeam);
            }
        });
    }

    @Override
    public void setList(List<PracticeTrendBean> beanList, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refresh.finishLoadMore();
        } else {
            loadMask.setStatus(LoadingLayout.Success);
            refresh.finishRefresh();
            mDataList.clear();
        }
        page++;
        mDataList.addAll(beanList);
        commonAdapter.notifyDataSetChanged();
    }

    @Override
    public void setError(String msg, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refresh.finishLoadMore();
            if (!NetUtil.isNetworkAvalible(getContext())) {
                showToast("网络异常，请检查您的网络！", 4);
            }
        } else {
            refresh.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            if (!NetUtil.isNetworkAvalible(getContext())) {
                loadMask.setErrorImage(R.drawable.error_network);
                loadMask.setErrorText("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                loadMask.setErrorImage(R.drawable.empty_content);
                loadMask.setErrorText(msg);
            } else {
                loadMask.setErrorImage(R.drawable.error_content);
                loadMask.setErrorText(msg);
            }
        }
    }

    private List<Image> initDatas(List<PracticeTrendBean.Images> beanList) {
        List<Image> images = new ArrayList<>();
        for (int i = 0; i < beanList.size(); i++) {
            images.add(new Image(beanList.get(i).getUrl(), 0, 0));
        }
        return images;
    }

    class Adapter extends NineAdapter {

        Adapter(Context context, List<Image> list) {
            super(context, list);
        }

        @Override
        public int getCount() {
            return (list == null) ? 0 : list.size();
        }

        @Override
        public String getUrl(int position) {
            return getItem(position) == null ? null : ((Image) getItem(position)).getUrl();
        }

        @Override
        public Object getItem(int position) {
            return (list == null) ? null : list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int i, View view) {
            ImageView iv = new ImageView(getContext());
            Glide.with(getContext())
                    .load(list.get(i).getUrl())
                    .apply(new RequestOptions().error(R.drawable.cover_normal_default).placeholder(R.drawable.cover_normal_default).centerCrop().optionalTransform(new GlideRoundTransform(4)))
                    .into(iv);
            return iv;
        }
    }
}
